package com.gxa.servlet;

import com.alibaba.fastjson.JSON;
import com.gxa.dto.ResponseResult;
import com.gxa.entity.Owner;
import com.gxa.service.OwnerService;
import com.gxa.service.impl.OwnerServiceImpl;
import com.gxa.utils.WriteJson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
@WebServlet("/owner/*")
public class OwnerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String path = requestURI.substring(requestURI.lastIndexOf("/")); // 截取数据接口

        OwnerService ownerService = new OwnerServiceImpl();

        if ("/queryAllOwner".equals(path)){
            doQueryAllOwner(req,resp,ownerService);
        }
    }

    /**
     * 查询所有的业主
     * @param req
     * @param resp
     * @param ownerService
     */
    private void doQueryAllOwner(HttpServletRequest req, HttpServletResponse resp, OwnerService ownerService) {
        List<Owner> ownerList = null;
        try {
            ownerList = ownerService.queryAllOwner();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
        ResponseResult result = new ResponseResult(0, "success", 0, ownerList);
        String toJSONString = JSON.toJSONString(result);
        System.out.println(toJSONString);


        WriteJson.writeJson(toJSONString,resp);
    }
}
